package cn.xsly.user.service.impl;

import cn.xsly.basic.constant.VerifyCodeConstant;
import cn.xsly.basic.exception.BusinessException;
import cn.xsly.basic.jwt.JwtUtils;
import cn.xsly.basic.jwt.LoginData;
import cn.xsly.basic.jwt.RsaUtils;
import cn.xsly.basic.util.AjaxResult;
import cn.xsly.basic.util.HttpUtil;
import cn.xsly.basic.util.Md5Utils;
import cn.xsly.basic.util.StrUtils;
import cn.xsly.org.mapper.EmployeeMapper;
import cn.xsly.system.domain.Menu;
import cn.xsly.user.constant.WxConstants;
import cn.xsly.user.domain.Logininfo;
import cn.xsly.user.domain.User;
import cn.xsly.user.domain.Wxuser;
import cn.xsly.user.dto.LoginDto;
import cn.xsly.user.mapper.LogininfoMapper;
import cn.xsly.user.mapper.UserMapper;
import cn.xsly.user.mapper.WxuserMapper;
import cn.xsly.user.service.ILogininfoService;
import cn.xsly.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    //账号登录
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //判空
        String account = loginDto.getAccount();
        String inputPwd = loginDto.getCheckPass();

        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(inputPwd)) {
            throw new BusinessException("登录信息不能为空");
        }
        //检验账号是否存在
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("该账号不存在");
        }
        //校验密码，获取密码加上颜值编码进行比对
        String password = logininfo.getPassword();
        String byMd5 = Md5Utils.encrypByMd5(inputPwd + logininfo.getSalt());
        if (!byMd5.equals(password)) {
            throw new BusinessException("密码错误");
        }
        if (!logininfo.getDisable()) {
            throw new BusinessException("该账号已被禁用");
        }
        //使用token将用户信息加密，返回给前端
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return map;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        //根据扫码登录的code，发送第二个请求
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID).replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);

        //转为json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //json转为object,从里面获取微信里面的token和openid
        JSONObject parse = JSONObject.parseObject(jsonStr);
        String access_token = parse.getString("access_token");
        String openid = parse.getString("openid");
        //根据openid去查微信用户
        Wxuser wxuser = wxuserMapper.byOpenId(openid);
        if (wxuser != null) {
            User user = userMapper.findById(wxuser.getUserId());
            if (user != null) {
                Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

                //使用token将用户信息加密，返回给前端
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);

                return AjaxResult.me().setResultObj(map);
            }
        }

        //3.2.如果没有查到 = 响应给前端token，openid，前端跳转到绑定页面
        return AjaxResult.me().setSuccess(false).setResultObj("?access_token=" + access_token + "&openid=" + openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //一：校验 - 空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("信息不能为空!!!");
        }

        //校验：绑定是否失效 - 防止直接访问http://bugtracker.itsource.cn/binder.html
        if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId)) {
            throw new BusinessException("绑定失效，请重新扫码!!!");
        }
        //二：校验 - 手机验证码是否过期 是否正确 [业务🗡:phone 验证码:时间戳]
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstant.BINDER_CODE_PREFIX + phone);
        if (obj == null) {
            throw new BusinessException("验证码过期!!!");
        }
        //redis保存的验证码  和 用户输入的验证码
        if (!obj.toString().split(":")[0].equals(verifyCode)) {
            throw new BusinessException("验证码错误!!!");
        }

        //三：通过ack和openid发送第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);
        //四：处理响应的数据：json字符串 - json对象 - 获取wxUser的信息
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);

        //五：绑定用户：将WxUser对象【第三个请求中获取】 与 User对象【通过手机创建】进行绑定
        User user = userMapper.loadByPhone(phone);
        if (user == null) {//根据电话没有找到user对象
            //通过phone创建User对象
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }

        //user一定会有。并且user_id也有
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);

        //免密登录
        Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

        //使用token将用户信息加密，返回给前端
        Map<String, Object> mapTemp = loginSuccessJwtHandler(logininfo);

        //响应数据给前端
        return AjaxResult.me().setResultObj(mapTemp);
    }
    //封住返回值：Map【token，logininfo】

    //做登录拦截
    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {

        Map<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        loginData.setLogininfo(logininfo);
        if (logininfo.getType() == 0) {//后台管理员
            //2.当前登录人的所有权限的sn集合 - 昨天写过了 - 直接调用方法
            List<String> permissions = employeeMapper.loadSnBylogininfoId(logininfo.getId());
            map.put("permissions", permissions);
            loginData.setPermissions(permissions);
            //3.当前登录人的所有二级菜单及其它的父级菜单【前端需要】 - 自己写 - 难点1
            List<Menu> menus = employeeMapper.loadMenusByLogininfoId(logininfo.getId());
            map.put("menus", menus);
            loginData.setMenus(menus);
        }
        try {
            //4.将以上三个数据装到LoginData  - 使用工具类进行加密【1 2】 - jwt串
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String token = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);//没有做刷新过期时间

            //二：将四个数据装到map进行返回。疑问：jwt串里面不是已经有登录信息，权限和菜单了吗？ - 前端没有做解密
            map.put("token", token);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //4.将以上四个数据添加到Map进行返回
        return map;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机密码
        String randomPwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }



    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        //现在微信已经将性别
        wxuser.setSex(Integer.parseInt(obj.getString("sex")));
        //地址：country + province + city
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));

        return wxuser;
    }


}
